package com.api.main.mvc.service.impl;

import com.api.main.mvc.dao.OrgUserRepository;
import com.api.main.mvc.dao.pojo.OrgUserDO;
import com.element.security.single.model.AuthUserE;
import com.element.security.single.service.IAuthUserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

@Service(value = "userDetailsService")
public class UserDetailsServiceImpl implements IAuthUserDetailsService {

    @Resource
    private OrgUserRepository orgUserRepository;

    @Override
    public AuthUserE loadUserByUsername(String userName) throws UsernameNotFoundException {
        if ("admin".equals(userName)) {
            AuthUserE authUser = new AuthUserE();
            authUser.setUserId("admin");
            authUser.setPassword(new BCryptPasswordEncoder().encode("123456"));
            return authUser;
        } else {
            throw new UsernameNotFoundException("用户不存在");
        }
    }

    @Override
    public AuthUserE loadUserByParams(Map<String, String> map) throws UsernameNotFoundException {
        String code = map.get("code");
        if ("user1".equals(code)) {
            orgUserRepository.update();
            OrgUserDO orgUserDO = orgUserRepository.getUser(map.get("user_name"));
            if (null != orgUserDO) {
                AuthUserE authUser = new AuthUserE();
                authUser.setUserId(orgUserDO.getUserName());
                authUser.setPassword(new BCryptPasswordEncoder().encode(orgUserDO.getPassword()));
                return authUser;
            }
        }
        throw new UsernameNotFoundException("用户不存在");
    }
}